import time
from datetime import datetime, timedelta

from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from info import constants
from info import user_login_data, db
from info.models import User, Category, News
from info.modules.admin import admin_bp
from info.utits.pic_storage import pic_storage
from info.utits.response_code import RET


@admin_bp.route('/add_category',methods=["POST"])
def add_category():
    """新增/编辑分类"""
    category_name = request.json.get("name")
    category_id = request.json.get("id")

    if not category_name:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")

    if category_id:
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="查询分类异常")

        if not category:
            return jsonify(errno=RET.NODATA,errmsg="分类不存在")
        category.name = category_name
    else:
        category = Category()
        category.name = category_name
        db.session.add(category)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存分类对象异常")

    return  jsonify(errno=RET.OK,errmsg="OK")


@admin_bp.route('/news_type',methods=["GET"])
def news_type():
    """分类页面展示"""
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.app.logger.error()
        return  jsonify(errno=RET.DBERR,errmsg="查询分类数据异常")

    category_dict_list = []
    for category in categories if categories else []:
        category_dict = category.to_dict()
        category_dict_list.append(category_dict)

    category_dict_list.pop(0)

    data = {
        "categories":category_dict_list
    }

    return render_template("admin/news_type.html",data=data)


@admin_bp.route('/news_edit_detail',methods=["POST","GET"])
def news_edit_detail():
    """新闻编辑详情页面接口"""

    if request.method =="GET":
        news_id = request.args.get("news_id")

        if not news_id:
            return Exception("参数不足")

        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="新闻查询异常")

        if not news:
            return abort(404)

        news_dict = news.to_dict() if news else None

        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="新闻分类查询异常")

        category_dict_list = []

        for category in categories if categories else []:
            category_dict = category.to_dict()
            category_dict["is_selected"] = False

            if category.id == news.category_id:
                category_dict_list.append(category_dict)

        category_dict_list.pop(0)

        data = {
            "news":news_dict,
            "categories":category_dict_list
        }

        return render_template("admin/news_edit_detail.html",data=data)

    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.form.get("index_image")
    content = request.form.get("content")
    news_id = request.form.get("news_id")

    if not all([title,category_id,digest,content,news_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")

    pic_name = None
    if index_image:
        try:
            index_image_data = index_image.read()

        except Exception as e:
            current_app.looger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg="读取图片数据异常")

        try:
            pic_name = pic_storage(index_image_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR,errmsg="上传到云存储失败")

    new = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.looger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询数据异常")

    if not news:
        return jsonify(errno=RET.NODATA,errmsg="新闻不存在")

    new.titlen = title
    news.category_id  = category_id
    news.digest = digest
    news.content = content

    if pic_name:
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + pic_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存新闻数据异常")
    return jsonify(errno=RET.OK,errmsg="发布新闻成功")


@admin_bp.route("/news_edit",methods=["POST","GET"])
def news_edit():
    p = request.args.get("p",1)

    try:
        p = int(p)

    except Exception as e:
        current_app.logger.error(e)
        p = 1

    keywords = request.args.get("keywords")
    filters = []
    if keywords:
        filters.append(News.title.contains(keywords))


    news_list = []
    current_page = 1
    total_page = 1

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询新闻列表数据异常")

    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_edit.html",data=data)


@admin_bp.route('/news_review_detail',methods=["POST","GET"])
@user_login_data
def news_review_detail():
    """新闻审核详情页面接口"""
    if request.method == "GET":
        news_id = request.args.get("news_id")
        if not news_id:
            return Exception("参数不足")

        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="查询新闻异常")

        if not news:
            abort(404)

        news_dict = news.to_dict() if news else None

        data = {
            "news":news_dict
        }
        return render_template("admin/news_review_detail.html",data=data)

    param_dict = request.json
    news_id = param_dict.get("news_id")
    action = param_dict.get("action")
    user = g.user

    if  not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")

    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")

    if action not in ["accept","reject"]:
        return jsonify(errno=RET.PARAMERR,errmsg="action参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询新闻异常")

    if not news:
        return jsonify(errno=RET.NODATA,errmsg="新闻不存在")

    if action == "accept":
        news.status = 0

    else:
        reason = request.json.get("reason")
        if reason:
            news.status = -1
            news.reason = reason

        else:
            return jsonify(errno=RET.PARAMERR,errmsg="请填写拒绝原因")

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存新闻异常")

    return jsonify(errno=RET.OK,errmsg="OK")


@admin_bp.route("/news_review",methods= ["GET"])
def news_review():
    """新闻审核页面展示"""
    print("news_review")
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    news_list = 1
    current_page = 1
    total_page = 1

    keywords = request.args.get("keywords")

    filters = [News.status!=0]
    if keywords:
        filters.append(News.title.constants(keywords))

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_list = paginate.items
        current_page  = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询分页数据异常")

    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news": news_dict_list,
        "current_page": current_page,
        "total_page":total_page
    }
    return render_template("admin/news_review.html",data=data)


@admin_bp.route('/user_list',methods=["POST","GET"])
@user_login_data
def user_list():
    """用户列表接口"""
    p = request.args.get("p",1)
    user = g.user
    try:
        p = int(p)

    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user_list =[]
    curren_page = 1
    total_page = 1
    try:
        paginate = User.query.filter(User.is_admin==False).order_by(User.create_time.desc()).paginate(p,constants.ADMIN_USER_PAGE_MAX_COUNT,False)
        user_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询分页数据异常")

    user_dict_list = []
    for user in user_list if user_list else []:
        user_dict_list.append(user.to_admin_dict())

    data = {
        "user_list":user_dict_list,
        "current_page":current_page,
        "total_page":total_page
    }
    return render_template("admin/user_list.html",data=data)


@admin_bp.route('/user_count', methods=["GET"])
def user_count():
    """用户数据统计接口"""
    total_count = 0
    print("user_count")
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        # todo

    mon_count = 0
    try:
        now = time.localtime()
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    day_count = 0
    try:
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    active_date = []
    active_count = []

    for i in range(0, 31):
        begin_date = now_date - timedelta(days=i)
        end_date = begin_date + timedelta(days=1)

        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)

        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_date": active_date,
        "active_count": active_count
    }
    return render_template('admin/user_count.html', data=data)


@admin_bp.route("/index", methods=["GET", "POST"])
@user_login_data
def admin_index():
    """管理员首页"""
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None
    }

    return render_template("admin/index.html", data=data)


@admin_bp.route('/login', methods=['GET', 'POST'])
def admin_login():
    """管理员用户登录接口"""
    if request.method == 'GET':
        user_id = session.get("user_id")
        is_admin = session.get("is_admin", False)

        if user_id and is_admin:
            return redirect(url_for("admin.admin_index"))

        else:
            return render_template("admin/login.html")

    name = request.form.get("username")
    password = request.form.get("password")

    if not all([name, password]):
        return render_template("admin/login.html", errmsg="参数不足")

    admin_user = None    #type:User

    try:
        admin_user = User.query.filter(User.mobile == name, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="查询管理员用户异常")

    if not admin_user:
        return render_template("admin/login.html", errmsg="管理员用户不存在")

    if not admin_user.check_password(password):
        return render_template("admin/login.html", errmsg="密码填写错误")

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="保存管理员用户异常")

    session["nick_name"] = name
    session["mobile"] = None
    session["user_id"] = admin_user.id
    session["is_admin"] = True

    return redirect(url_for("admin.admin_index"))
